//
//  AppDelegate.m
//  OperationPro
//
//  Created by yaxue wang on 16/8/26.
//  Copyright © 2016年 展鸿科技. All rights reserved.
//

#import "AppDelegate.h"
#import "UMMobClick/MobClick.h"
#import "MainNavBarViewController.h"
#import "HomeViewController.h"
#import "LoginViewController.h"
#import <BaiduMapAPI_Map/BMKMapComponent.h>
#import "AppDelegate_JPush.h"
#import <BaiduMapAPI_Utils/BMKUtilsComponent.h>
#import <BaiduMapAPI_Map/BMKMapComponent.h>
#import <BaiduMapAPI_Search/BMKSearchComponent.h>
#import <BaiduMapAPI_Map/BMKMapComponent.h>
#import <BaiduMapAPI_Location/BMKLocationComponent.h>
#import "HomeViewController.h"
#import "PersonCenterViewController.h"
#import "DiscussViewController.h"
#import "ForceUpdateView.h"
#define C_House [[[NSBundle mainBundle] bundleIdentifier] rangeOfString:@".house."].location != NSNotFound

@interface AppDelegate ()<BMKLocationServiceDelegate,BMKGeoCodeSearchDelegate>
{
    BMKMapManager* _mapManager;
    dispatch_source_t _timer ;
    BMKLocationService* _locService;
    double latitude;
    double longtitude;
    NSString *_cityName;
    NSString *_province;
    BMKGeoCodeSearch *_geocodesearch;
    BOOL isGeoSearch;

    
}
@property (nonatomic, strong) MainNavBarViewController *mainNavBarViewController;
@end

@implementation AppDelegate


- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{

    [NSThread sleepForTimeInterval:2.0];
    // 要使用百度地图，请先启动BaiduMapManager
    _mapManager = [[BMKMapManager alloc]init];
        BOOL ret = [_mapManager start:@"MePAs4vHArzcsoGN25BAghDmbK5yh5hX" generalDelegate:self];
        if (!ret) {
            echo(@"manager start failed!");
        }

  //统计
    UMConfigInstance.appKey = @"5927f5367666136c99000e0d";
    UMConfigInstance.channelId = @"App Store";
    [MobClick startWithConfigure:UMConfigInstance];//配置以上参数后调用此方法初始化SDK！
    //极光推送
    [self initJPushApplication:application didFinishLaunchingWithOptions:launchOptions];
    
    //登录之后主界面
    if ([CClass getCacheData:NSUD_Token]) {
        [self enter];
    }else{
        //// 登录界面
        [self login];
    }
    _geocodesearch = [[BMKGeoCodeSearch alloc] init];
    //编码服务的初始化(就是获取经纬度,或者获取地理位置服务)
    _geocodesearch.delegate = self;//设置代理为self
//    NSDictionary* infoDict =[[NSBundle mainBundle] infoDictionary];
//    NSString* versionNum =[infoDict objectForKey:@"CFBundleShortVersionString"];
//    [CClass HttpRequestTask:YES withUrl:@"appversion_showProVersion" withData:nil notifyError:YES onSuccess:^(BaseModel *model) {
//        NSString* netWorkversion;
//
//        if ([F_NSpace([model.B_data objectForKey:@"version"]) isEqualToString:@""])
//        {
//            netWorkversion=@"0";
//        }else
//        {
//            netWorkversion=[model.B_data objectForKey:@"version"];//本地大于等于网络的不更新
//        }
//        //是最新
//        if (([netWorkversion compare:versionNum options:NSNumericSearch]==NSOrderedAscending)||([netWorkversion compare:versionNum options:NSNumericSearch]==NSOrderedSame))  {
//            
//        //是最新
//          
//        }
//        else
//        {
//          
//        //不是最新的
//            NSString *text =[NSString stringWithFormat:@"当前版本V%@\n有新版本。",versionNum];
//            [ForceUpdateView showImg:[UIImage imageNamed:@"Ico_center_update"]Title:@"检测更新提示" BtnTitle:@"更新" context:text action:^(NSInteger index) {
//                [[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"https://itunes.apple.com/us/app/bei-te-wei-zhi-ye-ban/id1167926957?l=zh&ls=1&mt=8"]];
//                
//            }];
////
//            
//        }
//        
//        
//    } onError:^(BaseModel *model) {
//        
//    }];

    
    return YES;
}

- (MainNavBarViewController *)mainNavBarViewController{
    if (_mainNavBarViewController == nil) {
        _mainNavBarViewController = [[MainNavBarViewController alloc] initWithRootViewController:[HomeViewController new]];
    }
    return _mainNavBarViewController;
}

- (void) enter{
//    MainNavBarViewController *navController = [[MainNavBarViewController alloc] initWithRootViewController:[HomeViewController new]];
    [[(BaseViewController *) self.mainNavBarViewController.viewControllers.firstObject mainTabBar] setShowIndex:0];

    [self.window setRootViewController:self.mainNavBarViewController];
    

    //初始化BMKLocationService
    _locService = [[BMKLocationService alloc]init];
    _locService.delegate = self;
    //启动LocationService
    [_locService startUserLocationService];

    NSTimeInterval period = 15*60; //设置时间间隔
    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
     _timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, queue);
    dispatch_source_set_timer(_timer, dispatch_walltime(NULL, 0), period * NSEC_PER_SEC, 0); //每秒执行
    dispatch_source_set_event_handler(_timer, ^{
        dispatch_async(dispatch_get_main_queue(), ^{
            //初始化BMKLocationService
            _locService = [[BMKLocationService alloc]init];
            _locService.delegate = self;
            //启动LocationService
            [_locService startUserLocationService];
            
        });
       
        
        
    });
    dispatch_resume(_timer);

}

- (void) login{
    MainNavBarViewController *navController = [[MainNavBarViewController alloc] initWithRootViewController:[LoginViewController new]];
    [self.window setRootViewController:navController];
}

- (void)guide
{
    
}


- (void)applicationWillResignActive:(UIApplication *)application {
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}

- (void)applicationDidEnterBackground:(UIApplication *)application {
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
    [self JPushApplicationDidEnterBackground:application];
    PostNotification(@"Operation_EnterBackground");
  
    
}
- (void)canleTimer
{
    dispatch_source_cancel(_timer);

}

- (void)applicationWillEnterForeground:(UIApplication *)application {
    // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
    [self JPushApplicationWillEnterForeground:application];
    PostNotification(@"Operation_EnterForeground");
}
- (void) registerPush{
    [self registerJPush];
}

- (void) unRegisterPush{
    [self unRegisterJPush];
}
- (void)applicationDidBecomeActive:(UIApplication *)application {
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}

- (void)applicationWillTerminate:(UIApplication *)application {
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
    // Saves changes in the application's managed object context before the application terminates.
}
#pragma mark 定位
/**
 *用户位置更新后，会调用此函数
 *@param userLocation 新的用户位置
 */
- (void)didUpdateBMKUserLocation:(BMKUserLocation *)userLocation
{
    //关闭地位
    [_locService stopUserLocationService];
    [self onClickReverseGeocode];


}
-(void)onClickReverseGeocode  //发送反编码请求的.
{
    isGeoSearch = false;
    CLLocationCoordinate2D pt = (CLLocationCoordinate2D){0, 0};//初始化
    if (_locService.userLocation.location.coordinate.longitude!= 0
        && _locService.userLocation.location.coordinate.latitude!= 0) {
        //如果还没有给pt赋值,那就将当前的经纬度赋值给pt
        pt = (CLLocationCoordinate2D){_locService.userLocation.location.coordinate.latitude,
            _locService.userLocation.location.coordinate.longitude
        };
    }
    BMKReverseGeoCodeOption *reverseGeocodeSearchOption = [[BMKReverseGeoCodeOption alloc]init];//初始化反编码请求
    reverseGeocodeSearchOption.reverseGeoPoint = pt;//设置反编码的店为pt
    BOOL flag = [_geocodesearch reverseGeoCode:reverseGeocodeSearchOption];//发送反编码请求.并返回是否成功
    if(flag)
    {
        echo(@"反geo检索发送成功");
    }
    else
    {
        echo(@"反geo检索发送失败");
    }
}

-(void) onGetReverseGeoCodeResult:(BMKGeoCodeSearch *)searcher result:(BMKReverseGeoCodeResult *)result errorCode:(BMKSearchErrorCode)error
{
    
    _cityName = result.addressDetail.city;
    _province = result.addressDetail.province;
    for (int i = 0; i < result.poiList.count; i++) {
        
        BMKPoiInfo* poi = [result.poiList objectAtIndex:i];
        if (i==0) {
            latitude= poi.pt.latitude;
            longtitude = poi.pt.longitude;
            
        }
    }
    NSMutableDictionary *dic=[[NSMutableDictionary alloc]init];
    [dic setObject:[NSNumber numberWithDouble:latitude] forKey:@"latitude"];
    [dic setObject:[NSNumber numberWithDouble:longtitude]forKey:@"longitude"];
    if (_province==nil) {
        return;
    }
    if (_cityName==nil) {
        return;
    }
    [dic setObject:_province forKey:@"province"];
    [dic setObject:_cityName forKey:@"city"];

    [CClass HttpRequestTask:YES withUrl:@"location_sharedLocation" withData:dic notifyError:YES onSuccess:^(BaseModel *model) {
        echo(([NSString stringWithFormat:@"共享定位信息"]));

        
    } onError:^(BaseModel *model) {
        
    }];
}

@end
